package com.ihr360.job.core.listener;

import com.ihr360.job.core.ItemReadListener;
import com.ihr360.job.core.scope.context.SimpleStepContext;
import org.springframework.core.Ordered;

import java.util.Iterator;
import java.util.List;

public class CompositeItemReadListener<T> implements ItemReadListener<T> {

    private OrderedComposite<ItemReadListener<? super T>> listeners = new OrderedComposite<ItemReadListener<? super T>>();

    /**
     * Public setter for the listeners.
     *
     * @param itemReadListeners
     */
    public void setListeners(List<? extends ItemReadListener<? super T>> itemReadListeners) {
        this.listeners.setItems(itemReadListeners);
    }

    /**
     * Register additional listener.
     *
     * @param itemReaderListener
     */
    public void register(ItemReadListener<? super T> itemReaderListener) {
        listeners.add(itemReaderListener);
    }

    /**
     * Call the registered listeners in reverse order, respecting and
     * prioritising those that implement {@link Ordered}.
     * @see org.springframework.batch.core.ItemReadListener#afterRead(java.lang.Object)
     */
    @Override
    public void afterRead(T item) {
        for (Iterator<ItemReadListener<? super T>> iterator = listeners.reverse(); iterator.hasNext();) {
            ItemReadListener<? super T> listener = iterator.next();
            listener.afterRead(item);
        }
    }

    /**
     * Call the registered listeners in order, respecting and prioritising those
     * that implement {@link Ordered}.
     * @see org.springframework.batch.core.ItemReadListener#beforeRead()
     */
    @Override
    public void beforeRead(SimpleStepContext simpleStepContext) {
        for (Iterator<ItemReadListener<? super T>> iterator = listeners.iterator(); iterator.hasNext();) {
            ItemReadListener<? super T> listener = iterator.next();
            listener.beforeRead(simpleStepContext);
        }
    }

    /**
     * Call the registered listeners in reverse order, respecting and
     * prioritising those that implement {@link Ordered}.
     * @see org.springframework.batch.core.ItemReadListener#onReadError(java.lang.Exception)
     */
    @Override
    public void onReadError(SimpleStepContext simpleStepContext,Exception ex) {
        for (Iterator<ItemReadListener<? super T>> iterator = listeners.iterator(); iterator.hasNext();) {
            ItemReadListener<? super T> listener = iterator.next();
            listener.onReadError(simpleStepContext,ex);
        }
    }
}
